const ejs = require("ejs");
const fs = require("fs");
const marked = require("marked");
const browserSync = require("browser-sync");
let browser;
const server = () => {
  browser = browserSync.create();
  browser.init({
    server: {
      baseDir: "./",
      index: "index.html",
    },
  });
};
const init = (cb) => {
  //读取md内容
  const md = fs.readFileSync("README.md", "utf-8");
  ejs.renderFile(
    "./template.ejs",
    {
      title: "markdown 2 html",
      content: marked.parse(md),
    },
    (err, data) => {
      if (err) throw err;
      fs.writeFileSync("index.html", data);
      cb && cb();
    }
  );
};
fs.watchFile("README.md", (cur, prev) => {
  if (cur.mtime !== prev.mtime) {
    console.log("文件更新了");
    init(() => browser.reload());
  }
});
init(() => server());
